import paho.mqtt.client as mqtt

from mqtt.common.common_constant import CommonConstant
from mqtt.common.common_topic_enums import CommonTopics
from mqtt.callback.callback_manager import callbackManager
from mqtt.callback.drc_up_callback_handler import DrcUpCallbackHandler
from mqtt.callback.services_reply_callback_handler import ServicesReplyCallbackHandler
from mqtt.callback.event_callback_handler import EventCallbackHandler
class MqttSubscription:
    def __init__(self, broker_address="192.168.70.229", port=1883, username="", password=""):
        # 初始化 MQTT 客户端
        self.client = mqtt.Client()
        self.client.username_pw_set(username=username, password=password)
        self.broker_address = broker_address
        self.port = port
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        self.callback_manager = callbackManager()
        # 这里是话题和处理方法的映射
        self.topics = CommonTopics.get_topic_list()
        self.services_reply_callback = ServicesReplyCallbackHandler()
        self.drc_up_callback = DrcUpCallbackHandler()
        self.event_callback = EventCallbackHandler()

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Connected successfully to MQTT Broker")
            # 确保订阅了多个话题
            for topic in self.topics:
                client.subscribe(topic)
                print(f"Subscribed to topic '{topic}'")
        else:
            print(f"Failed to connect. Return code: {rc}")

    def on_disconnect(self, client, userdata, rc):
        print(f"Disconnected from MQTT Broker with code {rc}")

    def on_message(self, client, userdata, message):
        # print(f"话题'{message.topic}'收到的信息: '{message.payload}'")
        # 查找对应的回调方法并执行
        try:
            # 查找话题对应的回调函数
            if message.topic.endswith(CommonConstant.PRODUCT_TOPIC_OSD_SUFFIX):
                pass
            elif message.topic.endswith(CommonConstant.TOPIC_STATE_SUFFIX):
                pass
            elif message.topic.endswith(CommonConstant.TOPIC_SERVICES_REPLY_SUFFIX):
                self.services_reply_callback.handle(message.payload)
            elif message.topic.endswith(CommonConstant.TOPIC_DRC_UP_SUFFIX):
                self.drc_up_callback.handle(message.payload)
            elif message.topic.endswith(CommonConstant.TOPIC_EVENTS_SUFFIX):
                self.event_callback.handle(message.payload)
            else:
                print(f"没有找到处理话题 {message.topic} 的回调方法")

        except Exception as e:
            print(f"Error executing callback for topic '{message.topic}': {str(e)}")


    def start(self):
        # 连接到 MQTT 服务器
        self.client.connect(self.broker_address, self.port, keepalive=60)
        # 开始监听消息
        self.client.loop_forever()
